from flask import Flask, request as req
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_cors import CORS
import os
import logging

db = SQLAlchemy()

def create_app(config_name='default'):
    app = Flask(__name__)
    app.config.from_object(config_name)
    
    # 设置环境变量供服务类使用
    os.environ['DEEPSEEK_API_KEY'] = app.config.get('DEEPSEEK_API_KEY', '')
    os.environ['STABILITY_API_KEY'] = app.config.get('STABILITY_API_KEY', '')
    
    # 初始化数据库
    db.init_app(app)
    
    # 初始化JWT
    jwt = JWTManager(app)
    
    # 配置CORS
    CORS(app, resources={r"/api/*": {"origins": "*"}})
    
    # 注册蓝图
    from app.controllers.pages import auth_api, user_api, role_api
    from app.controllers.lyrics_storyboard import lyrics_api
    app.register_blueprint(auth_api)
    app.register_blueprint(user_api)
    app.register_blueprint(role_api)
    app.register_blueprint(lyrics_api)
    
    # 配置日志
    app.logger.setLevel(logging.INFO)
    
    @app.after_request
    def log_response(resp):
        app.logger.debug(f"{req.method} {req.url} - Status: {resp.status}")
        return resp
        
    return app